package com.mjf.net.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 文件上传客户端
 */
public class TCPFileUploadClient {
    public static void main(String[] args) throws Exception {

        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);

        // 创建读取磁盘文件的输入流，图片是二进制文件
        String filePath = "D:\\coding\\idea\\java-stu\\input\\image-rendered.png";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));

        // 获取文件对应的字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        bis.close();

        // 通过 Socket 将文件发送给服务端
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(bytes);
        socket.shutdownOutput();    // 关闭 Socket 输出流

        // 接收服务端的回执信息
        String ackInfo = StreamUtils.streamToString(socket.getInputStream());
        if(ackInfo.equals("success")) {
            System.out.println("文件拷贝成功");
        } else {
            System.out.println("文件拷贝失败");
        }

        bos.close();
        socket.close();

    }
}
